package cn.com.dhcc.app.pub.core.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;

import cn.com.dhcc.app.core.base.InterceptorBean.SIGNAL;
import cn.com.dhcc.app.core.base.log.LogType;
import cn.com.dhcc.app.core.boot.BootParam;
import cn.com.dhcc.app.core.component.db.orm.ModuleParser;
import cn.com.dhcc.app.core.exception.InitException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.listener.AppInitListener;
import cn.com.dhcc.app.pub.core.CM;
import cn.com.dhcc.app.pub.module.resmgr.service.ResourceService;

/**
 * 该监听器在Spring容器启动之后运行
 * 可以在这里预先处理一些业务逻辑
 */
public class MenuResourceInitLisener implements AppInitListener {
	private static Logger logger = cn.com.dhcc.app.core.component.log.Log.getLogger(LogType.SYSINNER);

	@Override
	public void init(ServletContextEvent contextEvent, BootParam bootParam) throws InitException {
		//将菜单资源加入缓存
		loadMenuToCache(contextEvent.getServletContext());
	}
	
	private void loadMenuToCache(ServletContext servletContext) {
		try {
			CM.getBean(ResourceService.class).loadResourceToCache();
			servletContext.log("将菜单资源加入缓冲成功...");
		} catch (ServiceException e) {
			servletContext.log("将菜单资源加入缓冲失败...", e);
		}
	}

	@SuppressWarnings("unused")
	private void parseModules(ServletContext servletContext) {
		ModuleParser.getInstance().parase(servletContext);
	}
	
	@Override
	public void destroyed(ServletContextEvent contextEvent, BootParam bootParam) throws InitException {
		logger.info("AfterSpringInitLisener destroyed...");
	}

	@Override
	public SIGNAL onError(ServletContextEvent contextEvent, BootParam bootParam)
			throws InitException {
		return SIGNAL.STOP;
	}
}
